/**
 * Created by yoyoyk on 2017/3/18.
 * Dalyn update on 2017/4/13.
 */
import React from "react";
import Relay from "react-relay";
import Confirm from '../../../common/Confirm';
import Select from '../../../common/Select';
import { Table, Icon, message, Tooltip } from 'antd';
import InputBox from '../../../common/InputBox';
import Packapply from './Packapply';
import Handlelog from './Handlelog';
import Reactkey from "../../../util/ReactKey";
import OrderdetailPartA from './OrderdetailPartA';
import OrderdetailPartB from './OrderdetailPartB';
import Util from "../../../util/Util";
import AddImgModal from "./AddImgModal";
import InfoOrderMutation from "../mutation/InfoOrderMutation";
import InfoEnquiryOrderMutation from '../mutation/InfoEnquiryOrderMutation';
import "./css/OrderDetail.css";

import OrderdetailContractInfo from './OrderdetailContractInfo'
import SupplementaryContract from './order_index/contract_management/SupplementaryContract';
// import OrderdetailAcceptButton from './OrderdetailAcceptButton'; //接单按钮

export default class Orderdetail_gms extends React.Component{
    constructor(props){
        super(props);
        this.state={
            num:0,
            arr:[],
            order:[],
            width:0,
            deliverRequests: [],
            isLoading: true,
        };
        this.orderpartA = "";
        this.orderpartB = "";
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.money={
            total:87887,pay:6786
        }
    }

    componentWillMount(){
        if(this.props.enquiryId !='' && this.props.enquiryId != undefined) {
            this.EnquiryOrderdetail();
        } else {
            this.Orderdetail();
        }
    }

    showOrderdetail(){
        if(this.props.enquiryId !='' && this.props.enquiryId != undefined) {
            this.EnquiryOrderdetail();
        } else {
            this.Orderdetail();
        }
    }

    EnquiryOrderdetail() {
        this.state.width=this.money.pay/this.money.total*460
        this.setState({
            arr:this.arr
        });
        /*infoorder接口*/
        let oid = this.props.orderId
        Relay.Store.commitUpdate(
            new InfoEnquiryOrderMutation({
                orderId: oid,
                enId: this.enterpriseId,
                enquiryId: this.props.enquiryId
            }),
            {
                onFailure: () => {
                    message.info('请求失败')
                    this.setState({
                        isLoading: false
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.infoEnquiryOrder.infoEnquiryOrder.errorCode;
                    if(errorCode=='0'){
                        let order = response.infoEnquiryOrder.infoEnquiryOrder.order;
                        let deliverRequests = response.infoEnquiryOrder.infoEnquiryOrder.order.deliverRequests
                        let orderGoodss = response.infoEnquiryOrder.infoEnquiryOrder.order.orderGoodss  //订单表格数据
                        orderGoodss.push({gid: 'key1'},{gid: 'key2'})   //push两条空数据，合计 合计大写
                        if (orderGoodss) {
                            orderGoodss.map((o,m) => {
                                if (o.quantity && o.price) {
                                    o.tableOrderMoney = (o.quantity*o.price).toFixed(2)
                                }
                                return o
                            })
                        }
                        deliverRequests.map((v, i)=> {
                            v.deliverDate = Util.dateFormat(v.deliverDate)   //时间戳转换
                            return v
                        })
                        this.orderpartA = order.partA;
                        this.setState({
                            order: order,
                            deliverRequests: deliverRequests,
                            isLoading: false
                        },()=>{
                            if(this.refs.ordercinfo){
                                this.refs.ordercinfo.setState({
                                    supplyContractsData : order.supplyContracts
                                });
                            }
                        });
                        this.props.orderDetail()
                    } else {
                        message.info('请求失败')
                    }
                }
            }
        )
    }

    Orderdetail() {
      this.state.width=this.money.pay/this.money.total*460
      this.setState({
          arr:this.arr
      });
      /*infoorder接口*/
      let oid = this.props.orderId
      Relay.Store.commitUpdate(
          new InfoOrderMutation({
              orderId: oid,
              enId: this.enterpriseId,
          }),
          {
              onFailure: () => {
                  message.info('请求失败')
                  this.setState({
                    isLoading: false
                  })
              },
              onSuccess: (response) => {
                  let errorCode = response.infoOrder.infoOrder.errorCode;
                  if(errorCode=='0'){
                      let order = response.infoOrder.infoOrder.order;
                      let deliverRequests = response.infoOrder.infoOrder.order.deliverRequests
                      let orderGoodss = response.infoOrder.infoOrder.order.orderGoodss  //订单表格数据
                      orderGoodss.push({gid: 'key1'},{gid: 'key2'})   //push两条空数据，合计 合计大写
                      if (orderGoodss) {
                        orderGoodss.map((o,m) => {
                          if (o.quantity && o.price) {
                            o.tableOrderMoney = (o.quantity*o.price).toFixed(2)
                          }
                          return o
                        })
                      }
                      deliverRequests.map((v, i)=> {
                        v.deliverDate = Util.dateFormat(v.deliverDate)   //时间戳转换
                        return v
                      })
                      this.orderpartA = order.partA;
                      this.setState({
                          order: order,
                          deliverRequests: deliverRequests,
                          isLoading: false
                      },()=>{
                        if(this.refs.ordercinfo){
                          this.refs.ordercinfo.setState({
                            supplyContractsData : order.supplyContracts
                          });
                        }
                      });
                      this.props.orderDetail()
                  } else {
                    message.info('请求失败')
                  }
              }
          }
      )
    }

    showImg(url){
        this.refs.addimg.setState({
            url:url,
            visible:true
        });
    }

    sumMoney() {   //合计  大小写
      let sumMoney = 0
      this.state.order.orderGoodss ? this.state.order.orderGoodss.map((v, i) => {
        if (v.quantity && v.price) {
          // sumMoney += (v.quantity*v.price)
          sumMoney += Number(v.tableOrderMoney)
        }
        return sumMoney
      }) : null
      return sumMoney.toFixed(2)
    }

    sumTotal() {
      let sumTotal = 0
      this.state.order.orderGoodss ? this.state.order.orderGoodss.map((v, i) => {
        if (v.quantity) {
          sumTotal += parseFloat(v.quantity)
        }
        return sumTotal
      }) : null
      return sumTotal.toFixed(3)
    }

    /*合同附件*/
    apply(){
        let contractUrl = [];
        let contractUrlSum = []
        if(this.state.order.contractUrl1){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl1))
            contractUrlSum.push(this.state.order.contractUrl1)
        }
        if(this.state.order.contractUrl2){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl2))
            contractUrlSum.push(this.state.order.contractUrl2)
        }
        if(this.state.order.contractUrl3){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl3))
            contractUrlSum.push(this.state.order.contractUrl3)
        }
        if(this.state.order.contractUrl4){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl4))
            contractUrlSum.push(this.state.order.contractUrl4)
        }
        if(this.state.order.contractUrl5){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl5))
            contractUrlSum.push(this.state.order.contractUrl5)
        }

        this.arr2 = contractUrl ? contractUrl : [];
        return this.arr2.map((item2,index)=>{
            return(
                <Packapply oArr={item2} item2={item2} contractUrlSum={contractUrlSum[index]}/>
            )
        })
    }

    opratelog(){
        this.refs.Handlelog.setState({
            visible : true
        })
    }

    render() {
        const columns = [
          {
            title: '交货时间',
            dataIndex: 'deliverDate',
            key: 'deliverDate',
          },
          {
            title: '数量',
            dataIndex: 'amount',
            key: 'amount',
          },
          {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
          }
        ];
        const columnsGoodsDetail = [
          {
            title: '款号',
            dataIndex: 'styleNo',
            key: 'styleNo',
            width: 200
          },
          {
            title: '品名',
            dataIndex: 'productName',
            key: 'productName',
            width: 200,
            render: ((text, record, index)=>{
              if(index == this.state.order.orderGoodss.length-2) {
                return '合计'
              } else if(index == this.state.order.orderGoodss.length-1) {
                return '合计(大写)'
              } else {
                return record.productName
              }
            })
          },
          {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-1) {
                obj.children = Util.numtoChinese(this.sumMoney())
                obj.props.colSpan  = 3;
                return obj
              } else if(index == this.state.order.orderGoodss.length-2) {
                obj.props.colSpan  = 9;
                return obj;
              } else {
                return record.description
              }
            })
          },
          {
            title: '颜色',
            dataIndex: 'colour',
            key: 'colour',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-1) {
                obj.props.colSpan = 0
                return obj
              } else if(index == this.state.order.orderGoodss.length-2) {
                return this.sumTotal()
              } else {
                return record.colour
              }
            })
          },
          {
            title: '花型图片',
            dataIndex: 'url',
            key: 'url',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-1) {
                obj.props.colSpan = 0
                return obj
              } else if(index == this.state.order.orderGoodss.length-2) {
                return this.sumMoney()
              } else if (record.url) {
                return (<img src={record.url} style={{width:140,height:33}} alt="" onClick={this.showImg.bind(this, record.url)}/>)
              }
            })
          },
          {
            title: '尺码',
            dataIndex: 'size',
            key: 'size',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.size
              }
            })
          },
          // {
          //   title: '尺码比例',
          //   dataIndex: 'specification',
          //   key: 'specification',
          //   width: 200,
          //   render: ((text, record, index)=>{
          //     const obj = {
          //       children: text,
          //       props: {},
          //     };
          //     if(index == this.state.order.orderGoodss.length-2) {
          //       obj.props.rowSpan = 0
          //       return obj
          //     } else {
          //       return record.specification
          //     }
          //   })
          // },
          {
            title: '船期',
            dataIndex: 'sailingDate',
            key: 'sailingDate',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.sailingDate
              }
            })
          },
          {
            title: '数量配比',
            dataIndex: 'datamatching',
            key: 'datamatching',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.datamatching
              }
            })
          },
          {
            title: 'PO号',
            dataIndex: 'poNumber',
            key: 'poNumber',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.poNumber
              }
            })
          },
          {
            title: '单位',
            dataIndex: 'prickle',
            key: 'prickle',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.prickle
              }
            })
          },
          {
            title: '单价',
            dataIndex: 'price',
            key: 'price',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.price
              }
            })
          },
          {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-1) {
                return ''
              } else if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return parseFloat(record.quantity).toFixed(3)
              }
            })
          },
          {
            title: '金额',
            dataIndex: 'tableOrderMoney',
            key: 'tableOrderMoney',
            width: 200,
            render: ((text, record, index)=>{
              const obj = {
                children: text,
                props: {},
              };
              if(index == this.state.order.orderGoodss.length-2) {
                obj.props.rowSpan = 0
                return obj
              } else {
                return record.tableOrderMoney
              }
            })
          },
          {
            title: '备注',
            dataIndex: 'desp',
            key: 'desp',
            width: 200,
            render:((text,record,index)=>{
              return text && text.length > 5 ? (
                <Tooltip placement="topLeft" title={text}>
                    <span className='order_detail_remark'>{text}</span>
                </Tooltip>
              ) : <span>{text}</span>
            })
          }
        ]
        return (
          <div className="orderdetail_box_style">
            {
              this.state.isLoading ?
                <div style={{background:'#fff',position: 'absolute',height: '100%',zIndex: '3'}}><Icon style={{left: '55%',position: 'fixed',top: '45%',fontSize: '24px'}} type="loading" /></div>
              :(

                <div className='orderdetail_box_style_contract'>
                    {/*合同信息*/}
                    {
                      // this.state.order && this.state.order.status >= 3 ? (
                      //
                      //   // <SupplementaryContract order={this.state.order} Orderdetail={this.Orderdetail.bind(this)} ref={'ordercinfo'}/>
                      // ) : null
                    }
                    {
                      // <p className="order_detail_title">
                      //     <i className="order_detail_tLine"></i>
                      //     <span className="order_detail_tText">订单详情</span>
                      // </p>
                    }
                      {
                          this.enterpriseId == this.orderpartA ?
                              <OrderdetailPartA Orderdetail={this.Orderdetail.bind(this)} order={this.state.order} serviceType={this.serviceType}  key={Reactkey.key}/>
                              :
                              <OrderdetailPartB Orderdetail={this.Orderdetail.bind(this)} oid={this.props.orderId} ref={'partb'} order={this.state.order} key={Reactkey.key}/>
                      }
                      {/*商品&服务明细*/}
                      <div style={{width: 1150, minHeight: 280}}>
                        <br/>
                        <Table
                          dataSource={this.state.order.orderGoodss}
                          rowKey={record => record.gid}
                          columns={columnsGoodsDetail}
                          className="columnsGoodsDetail"
                          bordered
                          scroll={{ x: 1150 }}
                          pagination={false}
                          title={() => '商品明细'}
                        />
                        { /*交货要求*/  }
                        <Table
                          dataSource={this.state.deliverRequests}
                          rowKey={record => record.did}
                          columns={columns}
                          className="requireTable"
                          bordered
                          pagination={false}
                          title={() => '交货要求'}
                        />
                        {/*备注*/}
                        <div className="order_detail_orderId_bz">
                            <p className="order_detail_addpart_orderp"  style={{borderBottom: '1px solid #f0f0f0'}}>备注</p>
                            <div className="order_detail_customer_info clear">
                              <p style={{width:50,height:30,float:'left',lineheight:"30px",fontSize:'14px', color: '#333'}}>备注:</p>
                              <p style={{float:'left',width:'950px'}}>{this.state.order.rmark}</p>
                              <br style={{clear: 'both'}} />
                              <p style={{width:50,height:30,float:'left',lineheight:"30px",fontSize:'14px', color: '#333'}}>附件:</p>
                              <p style={{float:'left',width:'950px'}}>
                                {
                                  this.apply()
                                }
                              </p>
                            </div>
                        </div>
                      </div>
                      {
                        this.state.order.partA != this.enterpriseId && (this.state.order.status == 1 || this.state.order.status == 2) ? (
                          <OrderdetailAcceptButton Orderdetail={this.showOrderdetail.bind(this)} order={this.state.order} />
                        ): null
                      }
                  </div>
              )
            }
            <AddImgModal ref="addimg" disn={'true'}/>
          </div>
        )
    }
}
